<?php
class RecordModel extends CommonModel
{
	public function __construct($uid)
	{
		parent::__construct('record');
	    if(empty($uid) || intval($uid) != $uid){trigger_error("UID ERROR!");exit;}
	    $this->uid = $uid;
	}
	
	protected function _setFields()
	{
		return array(
			'AID',
			'UID',
		    'IeItem',
			'AccountID',
			'Income',
			'Expend',
			'DiaryDate',
			'Remark'
		);
	}
	
	protected function _setPrimaryKeys()
	{
		return array(
			'AID'
		);
	}
	
	protected function _setAutoIncrementFields()
	{
		return array(
			'AID'
		);
	}
	
	protected function _setForeignKeyRelation()
	{
		return array();
	}
	
	public function add($data)
	{
		$data = $this->_getFieldsData($data);
		$dbMaster = DB::getMaster();
		$sql = "INSERT INTO `{$this->_table}`(`UID`, `IeItem`, `AccountID`,`Income`,`Expend`,`DiaryDate`,`Remark`) 
		VALUES('{$this->uid}', '{$data['IeItem']}', '{$data['AccountID']}','{$data['Income']}','{$data['Expend']}','{$data['DiaryDate']}','{$data['Remark']}')";
		
		$dbMaster->beginTransaction();
		$dbMaster->exec($sql);
		if($dbMaster->isError())
		{
			return false;
		}
		
		//更新账户资产
		$income = (float)($data['Income'] - $data['Expend']);
		
		$accountTable = Config::getConfig('DB_TABLE_PRE').'account';
		$sql = "UPDATE `{$accountTable}` SET `TotalAssets`=`TotalAssets`+{$income} 
				WHERE `AID`='{$data['AccountID']}'";
		
		$res = $dbMaster->exec($sql);
		if($dbMaster->isError())
		{
			$dbMaster->rollBack();
			return false;
		}
		
		$dbMaster->commit();
		return true;
	}
	
	public function getAll()
	{
		return $this->getData(null, null, null);
	}
	
	public function getData($itemID, $accountID, $recordID)
	{
		$where = '';
		$itemID != null && $where .= " AND i.AID={$itemID}";
		$accountID != null && $where .= " AND a.AID={$accountID}";
		$recordID != null && $where .= " AND c.AID={$recordID}";
		
		$dbSlave = DB::getSlave();
		$sql = "SELECT c.*,c.IeItem AS ItemNameID, IF(c.IeItem > 0, i.ItemName, '余额调整') AS ItemName, a.AccountName FROM `{$this->_table}` AS c 
				INNER JOIN ".Config::getConfig('DB_TABLE_PRE')."account AS a ON c.AccountID = a.AID
				left JOIN ".Config::getConfig('DB_TABLE_PRE')."ieitems AS i ON c.IeItem = i.AID
				WHERE c.UID='{$this->uid}'{$where}
				ORDER BY c.DiaryDate DESC, c.AID DESC";
		$result = $dbSlave->query($sql);
		return $result;
	}
	
	public function getRecord($aid)
	{
		return $this->getData(null, null, $aid);
	}
	
	public function getByAccount($aid = 0)
	{
	    return $this->getData(null, $aid, null);
	}
	
	/**
	 * 调整收支
	 * @param int $aid
	 * @param number $income
	 * @param number $expend
	 */
	public function amend($aid, $income, $expend)
	{
		$recordCls = new RecordModel($this->uid);
		$record = $recordCls->getRecord($aid);
		if(empty($record)){return -1;}
		
		$accountCls = new AccountModel($this->uid);
		$account = $accountCls->getAccountByID($record['AccountID']);
		if($account['Status'] == 0){return -2;}
		
		$dbMaster = DB::getMaster();
		$dbMaster->beginTransaction();
		
		$sql = "UPDATE `{$this->_table}` SET `Income`='{$income}', `Expend`='{$expend}' WHERE `AID`='{$aid}'";
		$dbMaster->exec($sql);
		if($dbMaster->isError())
		{
			return false;
		}
		
		$income = ($income - $record['Income']) - ($expend - $record['Expend']);
		$accountTable = Config::getConfig('DB_TABLE_PRE').'account';
		$sql = "UPDATE `{$accountTable}` SET `TotalAssets`=`TotalAssets`+{$income} 
				WHERE `AID`='{$record['AccountID']}'";
		$dbMaster->exec($sql);
		if($dbMaster->isError())
		{
			$dbMaster->rollBack();
			return false;
		}
		$dbMaster->commit();
		return true;
	}

	protected function _validationField($fieldName, $value) 
	{
		return true;
	}
	
	public function __destruct()
	{
		//echo 'account model destruct!';
	}
}